/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yuecai.modules.yc_supplier.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.yuecai.exception.BadRequestException;
import com.yuecai.modules.yc_goods.domain.YcGoods;
import com.yuecai.modules.yc_goods.repository.YcGoodsRepository;
import com.yuecai.modules.yc_supplier.domain.YcSupplier;
import com.yuecai.modules.yc_supplier.repository.YcSupplierRepository;
import com.yuecai.modules.yc_supplier.service.dto.YcSupplierDto;
import com.yuecai.modules.yc_supplier.service.dto.YcSupplierQueryCriteria;
import com.yuecai.modules.yc_supplier.service.mapstruct.YcSupplierMapper;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.PageUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yc_supplier
* @date 2020-06-26
**/
@Service
@RequiredArgsConstructor
public class YcSupplierService {

    private final YcSupplierRepository ycSupplierRepository;
    private final YcSupplierMapper ycSupplierMapper;
    private final YcGoodsRepository ycGoodsRepository;

    
    public Map<String,Object> queryAll(YcSupplierQueryCriteria criteria, Pageable pageable){
        Page<YcSupplier> page = ycSupplierRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ycSupplierMapper::toDto));
    }

    
    public List<YcSupplierDto> queryAll(YcSupplierQueryCriteria criteria){
        return ycSupplierMapper.toDto(ycSupplierRepository.findAll((root, criteriaQuery, criteriaBuilder)
                -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    
    @Transactional
    public YcSupplierDto findById(Long id) {
        YcSupplier ycSupplier = ycSupplierRepository.findById(id).orElseGet(YcSupplier::new);
        ValidationUtil.isNull(ycSupplier.getId(),"YcSupplier","id",id);
        return ycSupplierMapper.toDto(ycSupplier);
    }

    
    @Transactional(rollbackFor = Exception.class)
    public YcSupplierDto create(YcSupplier resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId()); 
        return ycSupplierMapper.toDto(ycSupplierRepository.save(resources));
    }

    
    @Transactional(rollbackFor = Exception.class)
    public void update(YcSupplier resources) {
        YcSupplier ycSupplier = ycSupplierRepository.findById(resources.getId()).orElseGet(YcSupplier::new);
        ValidationUtil.isNull( ycSupplier.getId(),"YcSupplier","id",resources.getId());
        ycSupplier.copy(resources);
        ycSupplierRepository.save(ycSupplier);
    }

    
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            List<YcGoods> bySupplierId = ycGoodsRepository.findBySupplierId(id);
            if (CollectionUtils.isNotEmpty(bySupplierId)){
                throw new BadRequestException("该供应商下还有关联的商品，请联系开发人员移除！");
            }
            ycSupplierRepository.deleteById(id);
        }
    }

    
    public void download(List<YcSupplierDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcSupplierDto ycSupplier : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("供应商名称", ycSupplier.getName());
            map.put("供货范围", ycSupplier.getSupplyScope());
            map.put("简介", ycSupplier.getSynopsis());
            map.put("联系方式", ycSupplier.getContactType());
            map.put("是否配送", ycSupplier.getDelivery());
            map.put("经度", ycSupplier.getLongitude());
            map.put("纬度", ycSupplier.getLatitude());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}